import React, { memo, useContext, useState, useEffect, useMemo } from 'react';
import { Spin, message, Tooltip, Form } from 'antd';
import { isSuccess } from '@/utils/request';
import { withRoutePage } from '@/utils/enhanceUtils';

import If from '@/components/If';

import { salaryRecheck, payoffService } from '@/services/salaryManage/salaryCalculate';

import EmptyPlaceHolder from '@/pages/SalaryManage/components/EmptyPlaceHolder';
import SalaryPageWrapper from '@/pages/SalaryManage/components/SalaryPageWrapper';
import SalaryPageProvider from '@/pages/SalaryManage/components/SalaryPageWrapper/SalaryPageProvider';
import BaseSettingProvider from '@/pages/SalaryManage/components/BaseSettingProvider';
import EmployeeNameWrapper from '@/pages/SalaryManage/components/EmployeeNameWrapper';

import { CHECK_STATUS } from '@/pages/SalaryManage/constant/recheckConstant';

import {
    summaryFieldChooser,
    numberFilter,
    orFilter
} from '@/pages/SalaryManage/SalaryCalculate/Recheck/SummaryProcessor';
import CheckBody from '@/pages/SalaryManage/SalaryCalculate/Recheck/components/CheckBody/index';
import OverviewHeader from '@/pages/SalaryManage/SalaryCalculate/Recheck/components/CheckHeader/index';
import { ColumnProcessor, CommonColumnInterceptor } from '@/pages/SalaryManage/SalaryCalculate/Recheck/ColumnProcessor';

import salaryStyle from '@/pages/SalaryManage/salaryManage.less';
import recheckStyles from '@/pages/SalaryManage/SalaryCalculate/Recheck/index.less';
import styles from './index.less';

const { queryGrantTableBodyData, queryGrantTableHeadData } = salaryRecheck;

const rowKey = 'id';

const { getExportInfo, getTableToolButtons } = payoffService;

const RecheckSummaryChooser = summaryFieldChooser(
    orFilter(numberFilter, col => ({
        success: col.dataIndex === 'employeeName',
        result: { [col.dataIndex]: '合计' }
    }))
);

const RecheckColumnProcessor = () =>
    new ColumnProcessor(
        {
            id: {
                hidden: true,
                fixed: true
            },
            employeeName: {
                fixed: true,
                width: 132,
                render: text => <EmployeeNameWrapper name={text} />
            },
            employeeNo: {
                fixed: true,
                width: 100
            },
            totalPayAmtRate: {
                scale: true,
                width: 170
            },
            hrCheckStatusName: {
                className: recheckStyles.pStatusCell,
                render(text, record) {
                    return (
                        <>
                            {record.hrCheckStatus === CHECK_STATUS.REJECT.code ? (
                                <Tooltip title={record.hrRemark} placement="bottomLeft">
                                    <i className="p-status-icon-reject" />
                                </Tooltip>
                            ) : null}
                            <div>{text}</div>
                        </>
                    );
                }
            },
            financeCheckStatusName: {
                className: recheckStyles.pStatusCell,
                render(text, record) {
                    return (
                        <>
                            {record.financeCheckStatus === CHECK_STATUS.REJECT.code ? (
                                <Tooltip title={record.financeCheckRemark} placement="bottomLeft">
                                    <i className="p-status-icon-reject" />
                                </Tooltip>
                            ) : null}
                            <div>{text}</div>
                        </>
                    );
                }
            }
        },
        CommonColumnInterceptor,
        null,
        []
    );

const DetailPage = memo(() => {
    const salaryProvider = useContext(SalaryPageProvider);
    const {
        period,
        organizationCode,
        searchModel,
        pagination,
        changeSalaryProviderParam,
        updateSignal
    } = salaryProvider;
    const [tableLoading, setTableLoading] = useState(false);
    const [exportInfo, setExportInfo] = useState(null);
    const [checkButtonList, setCheckButtonList] = useState([]);
    const [dataSource, setDataSource] = useState({
        list: [],
        total: null
    });
    const [headerSource, setHeaderSource] = useState([]);

    // 更新头部
    useEffect(() => {
        // 获取数据
        const getHeader = async () => {
            const year = period.substr(0, 4);
            const month = period.substr(5);
            const headerRes = await queryGrantTableHeadData({
                organizationCode,
                year,
                month,
                contrastType: searchModel.contrastType || 1
            });
            if (!isSuccess(headerRes)) {
                message.error(headerRes.msg);
                return;
            }
            setHeaderSource(headerRes.data);
        };
        if (period && organizationCode) {
            getHeader();
        }
    }, [period, organizationCode, searchModel.contrastType]);

    // 获取导出详细
    useEffect(() => {
        const getExport = async () => {
            const year = period.substr(0, 4);
            const month = period.substr(5);
            const exportInfoRes = await getExportInfo({
                year,
                month,
                organizationCode
            });

            if (isSuccess(exportInfoRes)) {
                setExportInfo(exportInfoRes.data);
            }
        };
        if (period && organizationCode) {
            getExport();
        }
    }, [period, organizationCode, updateSignal]);

    // 获取表单数据
    useEffect(() => {
        const getList = async () => {
            const year = period.substr(0, 4);
            const month = period.substr(5);
            setTableLoading(true);

            const { current, pageSize } = pagination;

            const tableRes = await queryGrantTableBodyData({
                organizationCode,
                year,
                month,
                nodeCode: 3,
                page: {
                    pageNo: current,
                    pageSize
                },
                ...searchModel
            });
            setTableLoading(false);

            if (!isSuccess(tableRes)) {
                setDataSource({
                    list: [],
                    total: 0
                });
                message.error(tableRes.msg);
                return;
            }
            const { rows, total } = tableRes.data;
            setDataSource({
                list: rows || [],
                total
            });
        };
        if (period && organizationCode) {
            getList();
        }
    }, [period, organizationCode, pagination, searchModel]);

    // 获取可操作按钮数组
    useEffect(() => {
        const getButtonFn = async () => {
            const year = period.substr(0, 4);
            const month = period.substr(5);
            const buttonRes = await getTableToolButtons({
                organizationCode,
                year,
                month
            });

            if (isSuccess(buttonRes)) {
                setCheckButtonList(buttonRes.data);
            } else {
                setCheckButtonList([]);
            }
        };
        if (period && organizationCode) {
            getButtonFn();
        }
    }, [period, organizationCode, updateSignal]);

    const memoDataSource = useMemo(
        () =>
            [].concat(dataSource.list).map(item => ({
                ...item,
                ...(item?.dynamicEmployeeInfo || {}),
                ...(item?.dynamicSalaryPayrollInfo || {})
            })),
        [dataSource.list]
    );

    return (
        <div className={salaryStyle.salaryWrapper}>
            <Spin spinning={tableLoading}>
                <OverviewHeader checkButtonList={checkButtonList} paymentTime={exportInfo?.paymentTime} />
                <If condition={exportInfo?.fileName}>
                    <Form layout="inline" className={styles.tableInfo}>
                        <Form.Item label="上次操作设置"></Form.Item>
                        <Form.Item label="操作人">
                            {' '}
                            <EmptyPlaceHolder value={exportInfo?.operator} />
                        </Form.Item>
                        <Form.Item label="付款日期">
                            <EmptyPlaceHolder value={exportInfo?.paymentTime} />
                        </Form.Item>
                        <Form.Item label="Excel表名">
                            <EmptyPlaceHolder value={exportInfo?.fileName} />
                        </Form.Item>
                        <Form.Item label="摘要">
                            <EmptyPlaceHolder value={exportInfo?.description} />
                        </Form.Item>
                        <Form.Item label="备注">
                            <EmptyPlaceHolder value={exportInfo?.remark} />
                        </Form.Item>
                    </Form>
                </If>

                <BaseSettingProvider organizationCode={organizationCode}>
                    <CheckBody
                        rowKey={rowKey}
                        tableHeader={headerSource}
                        columnProcessor={RecheckColumnProcessor()}
                        summaryFields={RecheckSummaryChooser()}
                        dataSource={memoDataSource}
                        changePage={changeSalaryProviderParam}
                        pagination={{
                            ...pagination,
                            total: dataSource.total
                        }}
                        hideSelection
                    />
                </BaseSettingProvider>
            </Spin>
        </div>
    );
});

const PayoffDetail = memo(({ location }) => (
    <SalaryPageWrapper
        type="salaryPayoffDetail"
        location={location}
        lastSearch
        tabProps={{
            type: 'detail',
            overviewUrl: '/finance/salary/calculate/salarypayoff/excelexport/collect',
            detailUrl: '/finance/salary/calculate/salarypayoff/excelexport/detail',
            logUrl: '/finance/salary/calculate/salarypayoff/excelexportlog'
        }}
    >
        <DetailPage />
    </SalaryPageWrapper>
));

export default withRoutePage(PayoffDetail);
